#include "ccp.h"
#include "DMA.h"
#define CCP_BUFFER_SIZE     4000    
#define CCP_TOTAL_BUFFER_SIZE 5000  
#define SYS_CPU_FRQ 144e6
#define CCP_TIME_FREQNCY  72e6 
uint16_t ccp_buffer[CCP_BUFFER_SIZE];  
STRCCPRegType g_ccp_strRegs;          
void fnCCP_Init(void);

void fnCCP_RealTime(void);
void fnCCP_Init(void){

		U32 tmpreg;
		memset(&g_ccp_strRegs, 0, sizeof(g_ccp_strRegs));
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;   
    RCC->APB2ENR |= RCC_APB2ENR_TIM1EN;    
    RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;    
    GPIOA->MODER &= ~GPIO_MODER_MODER8;    
    GPIOA->MODER |=  GPIO_MODER_MODER8_1; 
    GPIOA->OTYPER &= ~GPIO_OTYPER_OT_8;    
    GPIOA->OSPEEDR |= (GPIO_OSPEEDER_OSPEEDR8_0 | GPIO_OSPEEDER_OSPEEDR8_1); 
    GPIOA->PUPDR &= ~GPIO_PUPDR_PUPDR8;    
    GPIOA->AFR[1] |= 1 << (0*4);           
    TIM1->PSC = (SYS_CPU_FRQ / CCP_TIME_FREQNCY - 1);;        
    TIM1->ARR = 65535;     
    TIM1->CR1 &= ~TIM_CR1_DIR;


    TIM1->CCMR1 &= ~TIM_CCMR1_CC1S; 
    TIM1->CCMR1 |= TIM_CCMR1_CC1S_0; 
    

    TIM1->CCMR1 &= ~TIM_CCMR1_IC1F;
    

    TIM1->CCMR1 &= ~TIM_CCMR1_IC1PSC;
    

    TIM1->CCER &= ~TIM_CCER_CC1P;
    TIM1->CCER |= TIM_CCER_CC1E;  
    
		
    DMA2_Stream1->CR &= ~DMA_SxCR_EN;
    while (DMA2_Stream1->CR & DMA_SxCR_EN); 
    DMA2_Stream1->CR = 0;
    DMA2_Stream1->CR |= (DMA_SxCR_CHSEL_1 | DMA_SxCR_CHSEL_2); 
    DMA2_Stream1->CR |= DMA_SxCR_PL;      
    DMA2_Stream1->CR |= DMA_SxCR_MINC;    
    DMA2_Stream1->CR &= ~DMA_SxCR_DIR;   
    DMA2_Stream1->CR |= DMA_SxCR_CIRC;   
		DMA2_Stream1->CR |= DMA_SxCR_PSIZE_0;   
    DMA2_Stream1->CR |= DMA_SxCR_MSIZE_0;   

    DMA2_Stream1->PAR = (uint32_t)&(TIM1->CCR1); 
    DMA2_Stream1->M0AR = (uint32_t)ccp_buffer;
    DMA2_Stream1->NDTR = CCP_BUFFER_SIZE;
		
		
		
		
    TIM1->DIER |= TIM_DIER_CC1DE; 
    DMA2_Stream1->CR |= DMA_SxCR_EN;
		
		
    TIM1->BDTR |= TIM_BDTR_MOE; 
    TIM1->CR1 |= TIM_CR1_CEN;           
}

void fnCCP_RealTime(void)
{
    U16 curdet;
    U32 difftime = 0;
    float detfreq;
    U16 i;
    U16 bval;

    if(DMA_LISR_HTIF1 & DMA2->LISR){       
        bval = ccp_buffer[0];             
       
        for(i = 1; i < (CCP_BUFFER_SIZE / 2); i++)
        {
            if(ccp_buffer[i] != bval)
            {
                if(ccp_buffer[i] < bval) {
                    difftime += 65536;     
                }
                bval = ccp_buffer[i];
            }
        }
        
        difftime += (ccp_buffer[CCP_BUFFER_SIZE / 2 - 1] - ccp_buffer[0]);
        
        if(difftime > 0)
        {
            detfreq = (float)CCP_TIME_FREQNCY * (CCP_BUFFER_SIZE/2 - 1);
            detfreq /= difftime;          
            g_ccp_strRegs.freqs = detfreq; 
            g_ccp_strRegs.detfreq = TRUE;  
        }
        
        DMA1->LIFCR = DMA_LISR_HTIF1;      
    }
}

void fnCCP_Clear(void){
	g_ccp_strRegs.detfreq = FALSE;
}